/**
 * 功能说明：认证状态管理模块，包含登录、注销逻辑与 token 管理。
 */
import { loginApi, logoutApi } from '../../api/auth'

export default {
  namespaced: true,
  state: () => ({
    token: null,
    user: null
  }),
  getters: {
    isAuthenticated: (state) => !!state.token
  },
  mutations: {
    setAuth(state, { token, user }) {
      state.token = token
      state.user = user
    },
    clearAuth(state) {
      state.token = null
      state.user = null
    }
  },
  actions: {
    async login({ commit }, { username, password }) {
      // 关键逻辑：调用 API 完成登录并保存认证信息
      const data = await loginApi({ username, password })
      commit('setAuth', { token: data.token, user: data.user })
      return data
    },
    async logout({ commit }) {
      await logoutApi()
      commit('clearAuth')
    }
  }
}